package com.uzai.console.service.alarm.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.alarm.alarmrule.AlarmRuleIdDto;
import com.uzai.console.dto.alarm.alarmrule.AlarmRuleInfoDto;
import com.uzai.console.dto.alarm.alarmrule.AlarmRuleQuery;
import com.uzai.console.dto.alarm.alarmrule.AlarmRuleSetStatusDto;
import com.uzai.console.entity.AlarmContacter;
import com.uzai.console.entity.AlarmRule;
import com.uzai.console.entity.DingWarningGroup;
import com.uzai.console.mapper.AlarmContacterMapper;
import com.uzai.console.mapper.AlarmRuleMapper;
import com.uzai.console.mapper.DingWarningGroupMapper;
import com.uzai.console.service.alarm.AlarmRuleService;
import com.uzai.console.vo.alarm.alarmcontacter.AlarmContacterInfoVo;
import com.uzai.console.vo.alarm.alarmrule.AlarmRuleContentVo;
import com.uzai.console.vo.alarm.alarmrule.AlarmRuleInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 报警规则
 *
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class AlarmRuleServiceImpl implements AlarmRuleService {

    Logger logger = LoggerFactory.getLogger(AlarmRuleServiceImpl.class);

    @Autowired
    private AlarmRuleMapper alarmRuleMapper;
    @Autowired
    private AlarmContacterMapper alarmContacterMapper;
    @Autowired
    private DingWarningGroupMapper dingWarningGroupMapper;

    /**
     * 查询报警规则列表
     *
     * @param alarmRuleQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<AlarmRuleInfoVo> findAlarmRuleList(AlarmRuleQuery alarmRuleQuery) {
        //新建返回到页面的LIST对象
        List<AlarmRuleInfoVo> alarmRulePageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<AlarmRule> page = new Page<>();
        alarmRuleQuery.convert(page);
        ArrayList<AlarmRule> alarmRuleList = alarmRuleMapper.findByList(page, alarmRuleQuery);
        if (alarmRuleList != null && alarmRuleList.size() > 0) {
            for (AlarmRule alarmRule : alarmRuleList) {
                AlarmRuleInfoVo alarmRulePageVo = new AlarmRuleInfoVo();
                BeanUtils.copyProperties(alarmRule, alarmRulePageVo);

                //规则内容转化成list
                alarmRulePageVo.setAlarmRuleContentList(JSONObject.parseArray(alarmRule.getRuleInfo(), AlarmRuleContentVo.class));

                //报警联系人list
                List<Long> alarmContacterIdList = JSONObject.parseArray(alarmRule.getAlarmContacterIds(), Long.class);
                alarmRulePageVo.setAlarmContacterIdList(alarmContacterIdList);

                //封装联系人信息列表
                if (alarmContacterIdList != null && alarmContacterIdList.size() > 0) {
                    List<AlarmContacterInfoVo> alarmContacterInfoVoList = new ArrayList<>();
                    for (Long alermContacterId : alarmContacterIdList) {
                        AlarmContacterInfoVo alarmContacterInfoVo = new AlarmContacterInfoVo();
                        AlarmContacter alarmContacter = alarmContacterMapper.selectById(alermContacterId, alarmRuleQuery.getMerId());
                        if (alarmContacter != null) {
                            BeanUtils.copyProperties(alarmContacter, alarmContacterInfoVo);
                            alarmContacterInfoVoList.add(alarmContacterInfoVo);
                        } else {
                            DingWarningGroup dingWarningGroup = dingWarningGroupMapper.queryDingWarningGroupById(alermContacterId);
                            if (dingWarningGroup != null) {
                                alarmContacterInfoVo.setName(dingWarningGroup.getGroupName());
                                alarmContacterInfoVo.setNotifyAll(dingWarningGroup.getTipAllMember());
                                alarmContacterInfoVoList.add(alarmContacterInfoVo);
                            }
                        }
                    }
                    alarmRulePageVo.setAlarmContacterInfoVoList(alarmContacterInfoVoList);
                }

                alarmRulePageVoList.add(alarmRulePageVo);
            }
        }

        //返回到页面分页对象
        Page<AlarmRuleInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(alarmRulePageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询报警规则详情
     *
     * @param alarmRuleIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public AlarmRuleInfoVo findAlarmRuleInfo(AlarmRuleIdDto alarmRuleIdDto) {
        if (alarmRuleIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        AlarmRule alarmRule = alarmRuleMapper.selectById(alarmRuleIdDto.getId(), alarmRuleIdDto.getMerId());

        if (alarmRule == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报警规则不存在");
        }

        AlarmRuleInfoVo alarmRuleInfoVo = new AlarmRuleInfoVo();
        BeanUtils.copyProperties(alarmRule, alarmRuleInfoVo);

        //规则内容转化成list
        alarmRuleInfoVo.setAlarmRuleContentList(JSONObject.parseArray(alarmRule.getRuleInfo(), AlarmRuleContentVo.class));

        //报警联系人list
        List<Long> alarmContacterIdList = JSONObject.parseArray(alarmRule.getAlarmContacterIds(), Long.class);
        alarmRuleInfoVo.setAlarmContacterIdList(alarmContacterIdList);

        //封装联系人信息列表
        if (alarmContacterIdList != null && alarmContacterIdList.size() > 0) {
            List<AlarmContacterInfoVo> alarmContacterInfoVoList = new ArrayList<>();
            for (Long alermContacterId : alarmContacterIdList) {
                AlarmContacterInfoVo alarmContacterInfoVo = new AlarmContacterInfoVo();
                AlarmContacter alarmContacter = alarmContacterMapper.selectById(alermContacterId, alarmRuleIdDto.getMerId());
                if (alarmContacter != null) {
                    BeanUtils.copyProperties(alarmContacter, alarmContacterInfoVo);
                    alarmContacterInfoVoList.add(alarmContacterInfoVo);
                } else {
                    DingWarningGroup dingWarningGroup = dingWarningGroupMapper.queryDingWarningGroupById(alermContacterId);
                    if (dingWarningGroup != null) {
                        alarmContacterInfoVo.setName(dingWarningGroup.getGroupName());
                        alarmContacterInfoVo.setNotifyAll(dingWarningGroup.getTipAllMember());
                        alarmContacterInfoVoList.add(alarmContacterInfoVo);
                    }
                }
            }
            alarmRuleInfoVo.setAlarmContacterInfoVoList(alarmContacterInfoVoList);
        }
        return alarmRuleInfoVo;
    }

    /**
     * 添加报警规则
     *
     * @param alarmRuleInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void addAlarmRule(AlarmRuleInfoDto alarmRuleInfoDto) {

        if (StringUtils.isBlank(alarmRuleInfoDto.getDeviceType())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备类型");
        }

        if (StringUtils.isBlank(alarmRuleInfoDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入规则名称");
        }

        //判断页面是否输入手机号/邮箱/悠哉公众号openid/dingding机器人四项中的任意一项
//        Boolean flag = false;
//        if(alarmRuleInfoDto.getAlarmTypeMail() != null && alarmRuleInfoDto.getAlarmTypeMail() == 1){
//            flag = true;
//        }
//        if(alarmRuleInfoDto.getAlarmTypeMessage() != null && alarmRuleInfoDto.getAlarmTypeMessage() == 1){
//            flag = true;
//        }
//        if(alarmRuleInfoDto.getAlarmTypeDingding() != null && alarmRuleInfoDto.getAlarmTypeDingding() == 1){
//            flag = true;
//        }
//        if(alarmRuleInfoDto.getAlarmTypeWxpub() != null && alarmRuleInfoDto.getAlarmTypeWxpub() == 1){
//            flag = true;
//        }
//
//        if(!flag){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "报警渠道至少在 短信/邮箱/悠哉公众号/钉钉是否@所后人 四项中的选择一项");
//        }

//        if(alarmRuleInfoDto.getAlarmRuleContentList() == null || alarmRuleInfoDto.getAlarmRuleContentList().size() < 1){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "报警规则不能为空");
//        }

        AlarmRule alarmRule = new AlarmRule();
        BeanUtils.copyProperties(alarmRuleInfoDto, alarmRule);

        //手机报警值
        alarmRule.setMobileBatteryEnergy(Tools.getInteger(alarmRuleInfoDto.getMobileBatteryEnergy()));

        //报警联系人
        alarmRule.setAlarmContacterIds(Tools.getStrEmpty(JSONObject.toJSONString(alarmRuleInfoDto.getAlarmContacterIdList())));

        //报警规则
        alarmRule.setRuleInfo(Tools.getStrEmpty(JSONObject.toJSONString(alarmRuleInfoDto.getAlarmRuleContentList())));

        //默认开启
        alarmRule.setStatus(1);

        Integer now = DateUtil.getNowTime();
        alarmRule.setId(IdWorker.getId());
        alarmRule.setCreateTime(now);
        alarmRule.setUpdateTime(now);
        alarmRuleMapper.insertSelective(alarmRule);
    }

    /**
     * 修改报警规则
     *
     * @param alarmRuleInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateAlarmRule(AlarmRuleInfoDto alarmRuleInfoDto) {
        if (alarmRuleInfoDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if (StringUtils.isBlank(alarmRuleInfoDto.getDeviceType())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备类型");
        }

        if (StringUtils.isBlank(alarmRuleInfoDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入报警规则名称");
        }

//        //判断页面是否输入手机号/邮箱/悠哉公众号openid/dingding机器人四项中的任意一项
//        Boolean flag = false;
//        if(alarmRuleInfoDto.getAlarmTypeMail() != null && alarmRuleInfoDto.getAlarmTypeMail() == 1){
//            flag = true;
//        }
//        if(alarmRuleInfoDto.getAlarmTypeMessage() != null && alarmRuleInfoDto.getAlarmTypeMessage() == 1){
//            flag = true;
//        }
//        if(alarmRuleInfoDto.getAlarmTypeDingding() != null && alarmRuleInfoDto.getAlarmTypeDingding() == 1){
//            flag = true;
//        }
//        if(alarmRuleInfoDto.getAlarmTypeWxpub() != null && alarmRuleInfoDto.getAlarmTypeWxpub() == 1){
//            flag = true;
//        }
//
//        if(!flag){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "报警渠道至少在 短信/邮箱/悠哉公众号/钉钉是否@所后人 四项中的选择一项");
//        }

//        if(alarmRuleInfoDto.getAlarmRuleContentList() == null || alarmRuleInfoDto.getAlarmRuleContentList().size() < 1){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "报警规则不能为空");
//        }

        AlarmRule alarmRule = alarmRuleMapper.selectById(alarmRuleInfoDto.getId(), alarmRuleInfoDto.getMerId());

        if (alarmRule == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报警规则不存在");
        }

        alarmRule.setDeviceType(alarmRuleInfoDto.getDeviceType());
        alarmRule.setName(alarmRuleInfoDto.getName());
        alarmRule.setClientOut(Tools.getInteger(alarmRuleInfoDto.getClientOut()));
        alarmRule.setWechatOut(Tools.getInteger(alarmRuleInfoDto.getWechatOut()));
        alarmRule.setWechatDead(Tools.getInteger(alarmRuleInfoDto.getWechatDead()));
        alarmRule.setProductExpired(Tools.getInteger(alarmRuleInfoDto.getProductExpired()));
        alarmRule.setProductExpiredTime(Tools.getInteger(alarmRuleInfoDto.getProductExpiredTime()));
        alarmRule.setMobileBattery(Tools.getInteger(alarmRuleInfoDto.getMobileBattery()));
        alarmRule.setMobileBatteryEnergy(Tools.getInteger(alarmRuleInfoDto.getMobileBatteryEnergy()));
        alarmRule.setRuleInfo(Tools.getStrEmpty(JSONObject.toJSONString(alarmRuleInfoDto.getAlarmRuleContentList())));
        alarmRule.setSilentPeriod(alarmRuleInfoDto.getSilentPeriod());
        alarmRule.setStartTime(alarmRuleInfoDto.getStartTime());
        alarmRule.setEndTime(alarmRuleInfoDto.getEndTime());
        alarmRule.setAlarmContacterIds(Tools.getStrEmpty(JSONObject.toJSONString(alarmRuleInfoDto.getAlarmContacterIdList())));
        alarmRule.setAlarmTypeMessage(Tools.getInteger(alarmRuleInfoDto.getAlarmTypeMessage()));
        alarmRule.setAlarmTypeMail(Tools.getInteger(alarmRuleInfoDto.getAlarmTypeMail()));
        alarmRule.setAlarmTypeDingding(Tools.getInteger(alarmRuleInfoDto.getAlarmTypeDingding()));
        alarmRule.setAlarmTypeWxpub(Tools.getInteger(alarmRuleInfoDto.getAlarmTypeWxpub()));
        Integer now = DateUtil.getNowTime();
        alarmRule.setUpdateTime(now);
        alarmRuleMapper.updateById(alarmRule);
    }

    /**
     * 删除
     *
     * @param alarmRuleIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void deleteAlarmRule(AlarmRuleIdDto alarmRuleIdDto) {
        if (alarmRuleIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        alarmRuleMapper.deleteById(alarmRuleIdDto.getId(), alarmRuleIdDto.getMerId());
    }

    /**
     * 设置报警规则开启关闭
     *
     * @param alarmRuleSetStatusDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void setAlarmRuleStatus(AlarmRuleSetStatusDto alarmRuleSetStatusDto) {
        if (alarmRuleSetStatusDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if (alarmRuleSetStatusDto.getStatus() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入报警规则状态");
        }

        AlarmRule alarmRule = alarmRuleMapper.selectById(alarmRuleSetStatusDto.getId(), alarmRuleSetStatusDto.getMerId());

        if (alarmRule == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该报警规则不存在");
        }

        alarmRule.setStatus(alarmRuleSetStatusDto.getStatus());
        Integer now = DateUtil.getNowTime();
        alarmRule.setUpdateTime(now);
        alarmRuleMapper.updateById(alarmRule);
    }

}
